package net.dotool.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class RobotClient {

	public static void main(String[] args) {

		final String[] topics = { "Java", "Hadoop", "Spark", "Hive" };
		for (final String topic : topics) {
			new Thread() {
				private Selector selector = null;

				public void run() {
					try {
						try {
							selector = Selector.open();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						SocketChannel channel = SocketChannel.open(); // 新建服务端
						channel.configureBlocking(false);
						channel.connect(new InetSocketAddress("127.0.0.1", 8888)); // 连接服务端地址
						// 为该通道注册SelectionKey.OP_CONNECT事件
						channel.register(selector, SelectionKey.OP_CONNECT);
						listen();
					} catch (UnknownHostException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				int i = 0;

				public void listen() throws IOException {
					System.out.println(topic + "客户端启动");
					// 轮询访问selector
					while (true) {
						// 选择注册过的io操作的事件(第一次为SelectionKey.OP_CONNECT)
						selector.select();
						Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
						while (ite.hasNext()) {
							SelectionKey key = ite.next();
							// 删除已选的key，防止重复处理
							ite.remove();
							if (key.isConnectable()) {
								SocketChannel channel = (SocketChannel) key.channel();
								// 如果正在连接，则完成连接
								if (channel.isConnectionPending()) {
									channel.finishConnect();
								}
								// 向服务器发送消息
								channel.write(ByteBuffer.wrap(new String(topic + "_" + (i++)).getBytes()));
								// 连接成功后，注册接收服务器消息的事件
								channel.register(selector, SelectionKey.OP_READ);
								System.out.println("客户端连接成功");
							} else if (key.isReadable()) { // 有可读数据事件。
								SocketChannel channel = (SocketChannel) key.channel();

								ByteBuffer buffer = ByteBuffer.allocate(10);
								channel.read(buffer);
								byte[] data = buffer.array();
								String message = new String(data);

								System.out.println(message);
								
								channel.write(ByteBuffer.wrap(new String(topic + "_" + (i++)).getBytes()));

							}
						}
					}
				}
			}.start();

		}

	}

}
